<template>
  <div class="pie-chart-container">
    <!-- 数据统计卡片区域 -->
    <div class="data-stats">
      <div class="stat-card" v-for="(item, index) in chartData" :key="index">
        <div class="stat-label">{{ item.name }}</div>
        <div class="stat-value">{{ item.value }}</div>
        <div class="stat-percentage" v-if="total > 0">
          {{ ((item.value / total) * 100).toFixed(1) }}%
        </div>
      </div>
      <div class="stat-card total-card">
        <div class="stat-label">总人数</div>
        <div class="stat-value">{{ total }}</div>
      </div>
    </div>

    <!-- 饼图容器 -->
    <div ref="chartRef" class="chart-wrapper"></div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import * as echarts from 'echarts'
import userAPI from '../api/user_api.js'

export default {
  name: 'PieChart',
  setup() {
    // 图表容器引用
    const chartRef = ref(null)
    // 图表实例
    let myChart = null
    // 数据变量 - 存储处理后的图表数据
    const chartData = ref([]);

    // 计算总人数
    const total = computed(() => {
      return chartData.value.reduce((sum, item) => sum + item.value, 0)
    })

    // 初始化图表
    const initChart = () => {
      if (!chartRef.value) return

      myChart = echarts.init(chartRef.value)

      const option = {
        title: {
          text: '性别比例统计',
          subtext: '用户性别分布',
          left: 'center',
          textStyle: {
            fontSize: 18,
            fontWeight: 'bold'
          },
          subtextStyle: {
            fontSize: 14,
            color: '#666'
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          textStyle: {
            fontSize: 14
          }
        },
        series: [
          {
            name: '性别分布',
            type: 'pie',
            radius: '50%',
            data: chartData.value,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            label: {
              formatter: '{b}: {c} ({d}%)',
              fontSize: 12
            }
          }
        ]
      }

      myChart.setOption(option)
    }

    // 加载数据
    const loadData = async () => {
      try {
        console.log('开始请求数据...');
        const response = await userAPI.cgender();

        let data = null;
        if (response && typeof response === 'object') {
          data = response.data || response;
        }

        console.log('提取到的数据:', data);

        if (!data || typeof data !== 'object') {
          throw new Error('无法从响应中提取有效数据');
        }

        const dataEntries = Object.entries(data);
        console.log('数据键值对数组:', dataEntries);

        if (dataEntries.length < 2) {
          throw new Error('数据条目不足，至少需要2项数据');
        }

        // 转换为中文标签显示
        chartData.value = dataEntries.map(([name, value]) => ({
          name: name === 'male' ? '男性' : name === 'female' ? '女性' : name,
          value: Number(value) || 0
        }));

        console.log('处理后的图表数据:', chartData.value);
        initChart();
      } catch (error) {
        console.error('获取数据失败:', error.message);
        chartData.value = [
          { name: '男性', value: 0 },
          { name: '女性', value: 0 }
        ];
        initChart();
      }
    }

    // 处理窗口大小变化
    const handleResize = () => {
      if (myChart) {
        myChart.resize()
      }
    }

    // 组件挂载时加载数据并初始化图表
    onMounted(() => {
      loadData();
      window.addEventListener('resize', handleResize)
    })

    // 组件卸载时清理
    onUnmounted(() => {
      window.removeEventListener('resize', handleResize)
      if (myChart) {
        myChart.dispose()
        myChart = null
      }
    })

    return {
      chartRef,
      chartData,
      total
    }
  }
}
</script>

<style scoped>
.pie-chart-container {
  width: 100%;
  min-height: 600px;
  padding: 20px;
  box-sizing: border-box;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 数据统计卡片样式 */
.data-stats {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
  flex-wrap: wrap;
}

.stat-card {
  flex: 1;
  min-width: 150px;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.stat-percentage {
  font-size: 14px;
  color: #409eff;
  margin-top: 5px;
}

.total-card {
  background-color: #f0f7ff;
  border-left: 4px solid #409eff;
}

/* 图表容器样式 */
.chart-wrapper {
  width: 100%;
  height: 100%;
  min-height: 400px;
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-sizing: border-box;
}
</style>